package com.sample.springbatch.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 通过实现SchedulingConfigurer类配置接口实现定时任务
 * 可以动态修改cron表达式
 *
 * @author zwg
 * @date 2019-05-06 16:12
 **/
//@Component
//@EnableScheduling
public class SchedulingConfigurerService implements SchedulingConfigurer {
    Logger logger = LoggerFactory.getLogger(SchedulingConfigurerService.class);

    public static String task1_cron = "*/5 * * * * *";

    //模拟动态修改cron
    //@Scheduled(cron="0/5 * *  * * ? ")
    public void execute() {
        task1_cron = "0/20 * *  * * ? ";
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Task1(), new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 任务触发，可修改任务的执行周期
                CronTrigger trigger = new CronTrigger(task1_cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });

        scheduledTaskRegistrar.addTriggerTask(new Task2(), new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 任务触发，可修改任务的执行周期
                CronTrigger trigger = new CronTrigger(task1_cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }



    class Task1 implements Runnable{
        @Override
        public void run() {
            Long time = System.currentTimeMillis();
            logger.info("task1:{},{}",task1_cron, time);
            try{
                Thread.sleep(10000L);
            }catch (Exception e){

            }
        }
    }

    class Task2 implements Runnable{
        @Override
        public void run() {
            Long time = System.currentTimeMillis();
            logger.info("task2:{},{}",task1_cron, time);
            try{
                Thread.sleep(20000L);
            }catch (Exception e){

            }
        }
    }

}
